import java.util.Objects;
import java.util.Timer;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:定时器的实现
 * User: 邓大帅
 * Date: 2024-01-25
 * Time: 17:42
 */
class MyTask implements Comparable<MyTask> {
    public long time;
    public Runnable runnable = null;
    public MyTask(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time - o.time);
    }
}
class MyTimer {
    private PriorityBlockingQueue<MyTask> priorityBlockingQueue = new PriorityBlockingQueue<>();
    private Object locker = new Object();
    public void schedule(Runnable runnable,long time) {
        MyTask myTask = new MyTask(runnable,time);
        priorityBlockingQueue.put(myTask);
        synchronized (locker) {
            locker.notify();
        }
    }
    public MyTimer() {
        Thread thread = new Thread(() -> {
           while (true) {
               synchronized (locker) {
                   try {
                       MyTask myTask = priorityBlockingQueue.take();
                       if (myTask.time < System.currentTimeMillis()) {
                           myTask.runnable.run();
                       }else {
                            priorityBlockingQueue.put(myTask);
                            locker.wait(myTask.time - System.currentTimeMillis());
                       }
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }

               }
           }
        });
        thread.start();
    }
}
public class ThreadDemo6 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1");
            }
        },1000);
        System.out.println("0");
    }
}
